#!/bin/bash

scriptPath=$(dirname $0);

echo ".. merge database $1 << $2"

attach="attach '$2' as tmp;"

# backup rowid mappings
sh $scriptPath/createDatabaseMergeBackupRowidMappings.sh $2

# add data objects
query="INSERT OR IGNORE INTO table_dataobjects (id, xmlhdr, filepath, filename, datalen, num_attributes, signaturestatus, signee, createtime, receivetime, rxtime, source_iface_rowid, timestamp) SELECT id, xmlhdr, filepath, filename, datalen, num_attributes, signaturestatus, signee, createtime, receivetime, rxtime, source_iface_rowid, timestamp FROM tmp.table_dataobjects;"

sqlite3 -batch -separator ' ' $1 "$attach $query"

# add nodes
query="INSERT OR IGNORE INTO table_nodes (type, id, id_str, name, bloomfilter, num_attributes, sum_weights, resolution_max_matching_dataobjects, resolution_threshold, timestamp) SELECT type, id, id_str, name, bloomfilter, num_attributes, sum_weights, resolution_max_matching_dataobjects, resolution_threshold, timestamp FROM tmp.table_nodes;"

sqlite3 -batch -separator ' ' $1 "$attach $query"

# add attributes
query="INSERT OR IGNORE INTO table_attributes (name, value) SELECT name, value FROM tmp.table_attributes;"

sqlite3 -batch -separator ' ' $1 "$attach $query"

# add map dataobjects to attributes
query="INSERT OR IGNORE INTO table_map_dataobjects_to_attributes_via_rowid (dataobject_rowid, attr_rowid, timestamp) SELECT dataobject_rowid, attr_rowid, timestamp FROM tmp.table_map_dataobjects_to_attributes_via_rowid;"

sqlite3 -batch -separator ' ' $1 "$attach $query"

# add map dataobjects to attributes
query="INSERT OR IGNORE INTO table_map_nodes_to_attributes_via_rowid (node_rowid, attr_rowid, weight, timestamp) SELECT node_rowid, attr_rowid, weight, timestamp FROM tmp.table_map_nodes_to_attributes_via_rowid;"

sqlite3 -batch -separator ' ' $1 "$attach $query"




# SELECT m.dataobject_rowid, t.dataobjectId, m.ratio, devices, (t.devices like '%node-3%') as received FROM view_match_nodes_and_dataobjects_as_ratio as m LEFT JOIN table_dataobjects as d ON m.dataobject_rowid=d.rowid LEFT JOIN trace.dataobjects as t ON t.dataobjectId=lower(hex(d.id)) WHERE t.type='Data' AND m.ratio > 0 ORDER BY m.ratio desc;


